package com.example.detectivedemo;

import com.example.detectivedemo.application.PlayerAppService;
import com.example.detectivedemo.domain.player.Player;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.layout.DirectionLayout;
import ohos.agp.layout.LayoutAlignment;
import ohos.agp.utils.Color;
import ohos.agp.utils.TextAlignment;
import ohos.data.DatabaseHelper;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.Optional;

/**
 * 应用主界面切片
 * 负责显示玩家界面和处理用户交互
 */
public class MainAbilitySlice extends AbilitySlice {
    
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00203, "MainAbilitySlice");
    
    private PlayerAppService playerAppService;
    private Player currentPlayer;
    
    // UI组件
    private DirectionLayout rootLayout;
    private Text titleText;
    private Text statusText;
    private TextField usernameField;
    private TextField nicknameField;
    private Button registerButton;
    private Button loginButton;
    private Button logoutButton;
    private Button productButton;
    private Text playerInfoText;
    
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        
        // 初始化应用服务
        DatabaseHelper databaseHelper = new DatabaseHelper(this);
        playerAppService = PlayerAppService.getInstance(databaseHelper);
        
        // 创建UI界面
        createUI();
        
        HiLog.i(LABEL, "MainAbilitySlice onStart");
    }
    
    @Override
    public void onActive() {
        super.onActive();
        HiLog.i(LABEL, "MainAbilitySlice onActive");
    }
    
    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
        HiLog.i(LABEL, "MainAbilitySlice onForeground");
    }
    
    // 创建UI界面
    private void createUI() {
        // 创建根布局
        rootLayout = new DirectionLayout(this);
        rootLayout.setWidth(DirectionLayout.LayoutConfig.MATCH_PARENT);
        rootLayout.setHeight(DirectionLayout.LayoutConfig.MATCH_PARENT);
        rootLayout.setOrientation(Component.VERTICAL);
        rootLayout.setAlignment(LayoutAlignment.CENTER);
        rootLayout.setBackgroundColor(new Color(0x000000)); // 黑色背景
        
        // 创建标题文本
        titleText = new Text(this);
        titleText.setText("侦探推理解密游戏");
        titleText.setTextSize(50);
        titleText.setTextColor(new Color(0xFFFFFF)); // 白色文字
        titleText.setTextAlignment(TextAlignment.CENTER);
        titleText.setMarginBottom(50);
        rootLayout.addComponent(titleText);
        
        // 创建状态文本
        statusText = new Text(this);
        statusText.setText("欢迎来到侦探推理解密游戏！");
        statusText.setTextSize(20);
        statusText.setTextColor(new Color(0xFFFFFF));
        statusText.setTextAlignment(TextAlignment.CENTER);
        statusText.setMarginBottom(30);
        rootLayout.addComponent(statusText);
        
        // 创建用户名输入框
        usernameField = new TextField(this);
        usernameField.setWidth(500);
        usernameField.setHeight(80);
        usernameField.setHint("请输入用户名");
        usernameField.setTextColor(new Color(0xFFFFFF));
        usernameField.setHintColor(new Color(0x888888));
        usernameField.setMarginBottom(20);
        rootLayout.addComponent(usernameField);
        
        // 创建昵称输入框
        nicknameField = new TextField(this);
        nicknameField.setWidth(500);
        nicknameField.setHeight(80);
        nicknameField.setHint("请输入昵称");
        nicknameField.setTextColor(new Color(0xFFFFFF));
        nicknameField.setHintColor(new Color(0x888888));
        nicknameField.setMarginBottom(30);
        rootLayout.addComponent(nicknameField);
        
        // 创建注册按钮
        registerButton = new Button(this);
        registerButton.setText("注册");
        registerButton.setWidth(200);
        registerButton.setHeight(80);
        registerButton.setTextSize(25);
        registerButton.setTextColor(new Color(0x000000));
        registerButton.setBackgroundColor(new Color(0x00FF00)); // 绿色
        registerButton.setMarginBottom(20);
        registerButton.setClickedListener(component -> onRegisterClicked());
        rootLayout.addComponent(registerButton);
        
        // 创建登录按钮
        loginButton = new Button(this);
        loginButton.setText("登录");
        loginButton.setWidth(200);
        loginButton.setHeight(80);
        loginButton.setTextSize(25);
        loginButton.setTextColor(new Color(0x000000));
        loginButton.setBackgroundColor(new Color(0x0000FF)); // 蓝色
        loginButton.setMarginBottom(20);
        loginButton.setClickedListener(component -> onLoginClicked());
        rootLayout.addComponent(loginButton);
        
        // 创建退出登录按钮
        logoutButton = new Button(this);
        logoutButton.setText("退出登录");
        logoutButton.setWidth(200);
        logoutButton.setHeight(80);
        logoutButton.setTextSize(25);
        logoutButton.setTextColor(new Color(0x000000));
        logoutButton.setBackgroundColor(new Color(0xFFFF00)); // 黄色
        logoutButton.setMarginBottom(20);
        logoutButton.setClickedListener(component -> onLogoutClicked());
        logoutButton.setVisibility(Component.HIDE); // 初始隐藏
        rootLayout.addComponent(logoutButton);
        
        // 创建产品列表按钮
        productButton = new Button(this);
        productButton.setText("查看产品列表");
        productButton.setWidth(200);
        productButton.setHeight(80);
        productButton.setTextSize(25);
        productButton.setTextColor(new Color(0x000000));
        productButton.setBackgroundColor(new Color(0xFF6600)); // 橙色
        productButton.setMarginBottom(30);
        productButton.setClickedListener(component -> onProductButtonClicked());
        rootLayout.addComponent(productButton);
        
        // 创建玩家信息文本
        playerInfoText = new Text(this);
        playerInfoText.setText("");
        playerInfoText.setTextSize(20);
        playerInfoText.setTextColor(new Color(0xFFFFFF));
        playerInfoText.setTextAlignment(TextAlignment.CENTER);
        playerInfoText.setMarginBottom(30);
        rootLayout.addComponent(playerInfoText);
        
        // 设置根布局为内容
        super.setUIContent(rootLayout);
    }
    
    // 注册按钮点击事件
    private void onRegisterClicked() {
        String username = usernameField.getText();
        String nickname = nicknameField.getText();
        
        if (username.isEmpty() || nickname.isEmpty()) {
            statusText.setText("用户名和昵称不能为空！");
            statusText.setTextColor(new Color(0xFF0000)); // 红色
            return;
        }
        
        try {
            currentPlayer = playerAppService.registerPlayer(username, nickname);
            statusText.setText("注册成功！欢迎，" + nickname + "！");
            statusText.setTextColor(new Color(0x00FF00)); // 绿色
            updatePlayerInfo();
            logoutButton.setVisibility(Component.VISIBLE);
        } catch (IllegalArgumentException e) {
            statusText.setText("注册失败：" + e.getMessage());
            statusText.setTextColor(new Color(0xFF0000)); // 红色
        }
    }
    
    // 登录按钮点击事件
    private void onLoginClicked() {
        String username = usernameField.getText();
        
        if (username.isEmpty()) {
            statusText.setText("用户名不能为空！");
            statusText.setTextColor(new Color(0xFF0000)); // 红色
            return;
        }
        
        try {
            currentPlayer = playerAppService.loginPlayer(username);
            statusText.setText("登录成功！欢迎回来，" + currentPlayer.getNickname() + "！");
            statusText.setTextColor(new Color(0x00FF00)); // 绿色
            updatePlayerInfo();
            logoutButton.setVisibility(Component.VISIBLE);
        } catch (IllegalArgumentException e) {
            statusText.setText("登录失败：" + e.getMessage());
            statusText.setTextColor(new Color(0xFF0000)); // 红色
        }
    }
    
    // 退出登录按钮点击事件
    private void onLogoutClicked() {
        if (currentPlayer != null) {
            playerAppService.logoutPlayer(currentPlayer.getPlayerId());
            statusText.setText("已退出登录！");
            statusText.setTextColor(new Color(0xFFFFFF)); // 白色
            playerInfoText.setText("");
            currentPlayer = null;
            logoutButton.setVisibility(Component.HIDE);
        }
    }
    
    // 更新玩家信息显示
    private void updatePlayerInfo() {
        if (currentPlayer != null) {
            String info = "玩家信息：\n" +
                    "昵称：" + currentPlayer.getNickname() + "\n" +
                    "等级：" + currentPlayer.getLevel() + "\n" +
                    "经验值：" + currentPlayer.getExperience() + "\n" +
                    "解决案件数：" + currentPlayer.getSolvedCases() + "\n" +
                    "总得分：" + currentPlayer.getTotalScore();
            playerInfoText.setText(info);
        }
    }
    
    // 产品列表按钮点击事件
    private void onProductButtonClicked() {
        try {
            // 创建跳转到产品界面的Intent
            Intent intent = new Intent();
            intent.setParam("from", "MainAbility");
            
            // 启动ProductAbility
            present(new com.example.detectivedemo.ui.ProductAbilitySlice(), intent);
            
            HiLog.i(LABEL, "Navigating to ProductAbility");
        } catch (Exception e) {
            statusText.setText("跳转到产品界面失败：" + e.getMessage());
            statusText.setTextColor(new Color(0xFF0000)); // 红色
            HiLog.e(LABEL, "Failed to navigate to ProductAbility: " + e.getMessage());
        }
    }
}